﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Controls;
using System.Xml.Serialization;
using BaseControls;
using Engine.Scenario;
using System.Windows;

namespace Engine
{
    public enum MusicUpdate { update,start,stop };
    /// <summary>
    /// Main class that represent game engine.
    /// </summary>
    public class Game
    {       
        public Game(Player player,string scenarioFileName)
        {
            this.script = Scenario.Scenario.LoadScript(scenarioFileName);
            this.player = player;
            this.controlConstructor = new ControlConstructor();
            this.controlConstructor.GameEvent += new GameEventHandler(OnGameEvent);
            this.controlConstructor.Created += new LevelConstructedDelegate(LevelConstructed);
            this.controlConstructor.StartCreating += new StartConstructingDelegate(LevelStartConstructing);
            this.controlConstructor.LoadingProgressChange += new ProgressChangeDelegate(() => 
            { 
                if (LoadingChange != null)
                    LoadingChange(); 
            });
        }

        #region Fields const events.

        private int currentLevelId;
        private LevelData currentLevelData;
        /// <summary>
        /// Class for loading data from text file into structures.
        /// </summary>
        private Scenario.Scenario script;
        private ControlConstructor controlConstructor; 
        private Player player;

        public const string IsolatedStorageSaveGame = "HOGSaveGame";

        public Player Player
        {
            get { return player; }
            set { player = value; }
        }

        #endregion

        #region Events.

        public event LevelReadyDelegate LevelReady;
        public event StartConstructingDelegate StartLoadingLevel;
        public event GameEventHandler GameEvent;
        public event ProgressChangeDelegate LoadingChange;

        #endregion                

        #region Options methods.

        /// <summary>
        /// Start the game.
        /// </summary>
        public void NewGame()
        {
            //loading game script
            loadLevel(Scenario.Scenario.FirstLevelId);
        }

        /// <summary>
        /// Load game from file in isolated storage
        /// due to xml its really simple to hack the game :)
        /// </summary>        
        public void LoadGame()
        {
            try
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IsolatedStorageSaveGame, FileMode.Open, isf);
                XmlSerializer serializer = new XmlSerializer(typeof(Save));
                object o = serializer.Deserialize(isfs);

                Save s = o as Save;
                if (s != null)
                {
                    currentLevelId = s.LevelId;
                    player.Points = s.Points;
                    player.TimePlay = s.TimePlay;
                }
                else
                    throw new Exception();

                isfs.Close();
                loadLevel(currentLevelId);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        /// <summary>
        /// Serializes Save class into IsolatedStorage
        /// just marked; stored in db on server side in future
        /// due to xml its really simple to hack the game :)
        /// </summary>
        public void SaveGame()
        {
            Save save = new Save { LevelId = currentLevelId, Points = player.Points, TimePlay = player.TimePlay };
            try
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IsolatedStorageSaveGame, FileMode.Create, isf);
                XmlSerializer serializer = new XmlSerializer(typeof(Save));
                serializer.Serialize(isfs, save);
                isfs.Close();
            }
            catch (FileNotFoundException exc)
            {
                throw exc;
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }

        public void Exit()
        {
            //send all to 
        }
        /// <summary>
        /// This method reload music and sounds.
        /// </summary>
        public void UpdateMusic(MusicUpdate updateType)
        {
            try
            {
                if (controlConstructor != null)
                {
                    BaseLevel level = controlConstructor.GetActualLevel();
                    if (level == null)
                        return;
                    switch (updateType)
                    {
                        case MusicUpdate.start:
                            {
                                level.PlayMusic();
                                break;
                            }
                        case MusicUpdate.stop:
                            {
                                level.StopMusic();
                                break;
                            }
                        case MusicUpdate.update:
                            {
                                level.UpdateMusic();
                                break;
                            }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error while update music. Orginal message: " + e.Message);
            }
        }
        #endregion

        /// <summary>
        /// Starts game from provided level
        /// </summary>
        /// <param name="levelId">LevelId from which to start</param>
        private void loadLevel(int levelID)
        {            
            currentLevelData = script.GetLevelData(levelID);
            controlConstructor.LoadLevel(currentLevelData.XamlFilePath);
            currentLevelId = levelID;                        
        }

        /// <summary>
        /// Loading next level
        /// </summary>
        /// <returns>If level is not last return true</returns>
        public bool LoadNextLevel()
        {            
            if (currentLevelData.IDnextLevel != Scenario.Scenario.GameOverId)
            {
                currentLevelId = currentLevelData.IDnextLevel;
                loadLevel(currentLevelId);
                return true;
            }
            else
                return false;            
        }

        #region EventHandlers
        /// <summary>
        /// Main game event channel.
        /// </summary>        
        private void OnGameEvent(object data,GameChangeType type)
        {
            switch (type)
            {
                case GameChangeType.ItemComplete: { break; }//we just need LevelComplete event in this class
                case GameChangeType.LevelComplete: { LevelFinished(); break; }
            }
            if (GameEvent != null)
                GameEvent(data, type);
        }
        /// <summary>
        /// Event that is raised in ControlConstructor.
        /// </summary>
        /// <param name="levelControl">Control that is created</param>
        void LevelConstructed(Control levelControl)
        {
            if (LevelReady != null)
                LevelReady(levelControl, currentLevelData.Time);                         
        }
        /// <summary>
        /// Event that is raised when game engine know how many resources he need to download.
        /// </summary>
        /// <param name="count">Count of resources to download</param>
        void LevelStartConstructing(int count)
        {
            if (StartLoadingLevel != null)
                StartLoadingLevel(count);
        }
        #endregion

        /// <summary>
        /// After finish level game engine calculate points.
        /// </summary>
        /// <param name="goodClicks">How many click on items user do in game</param>
        /// <param name="badClicks">How many click on level user do in game</param>
        /// <param name="time">How many times user spend on level</param>
        public void AddPoints(int goodClicks, int badClicks, int time)
        {
            int pointsForLevel = currentLevelData.PointsForLevel +
                goodClicks * currentLevelData.PointsForItem +
                badClicks * currentLevelData.PenaltyForWrongClick +
                time * currentLevelData.PointsForSecond;

            player.Points += pointsForLevel;
            player.TimePlay += time;
        }
        public IEnumerable<string> GetItems()
        {
            return controlConstructor.GetItems();
        }
        /// <summary>
        /// Method raised after finished level.
        /// </summary>
        void LevelFinished()
        {
            SaveGame();            
        }
    }
}
